package barrier;

import com.ibm.tspaces.Field;
import com.ibm.tspaces.Tuple;
import com.ibm.tspaces.TupleSpace;
import com.ibm.tspaces.TupleSpaceException;

public class Barrier {
  String     name;
  TupleSpace space;
  Tuple      tuple;
  Tuple      template;

  public Barrier(String name, TupleSpace space) 
  throws TupleSpaceException {
    this.name  = name;
    this.space = space;
    template   = new Tuple(name, new Field(Integer.class));
  }

  public void init() 
  throws TupleSpaceException {
    tuple = new Tuple(name, new Integer(0));
    space.write(tuple);
  }

  public void barrier(int n) 
  throws TupleSpaceException {
    tuple = space.waitToTake(template);

    int count = (Integer) tuple.getField(1).getValue();
    tuple = new Tuple(name, new Integer(count + 1));
    space.write(tuple);

    tuple = new Tuple(name, new Integer(n));
    space.waitToRead(tuple);
  }

}
